import './index.scss';
import React, { useEffect, useState, useRef } from "react";
import { Dropdown, Radio, Space, Button, Popup, Empty } from 'antd-mobile'
import { DeleteOutline } from 'antd-mobile-icons'
import { Tabs } from 'antd-mobile'
import { chainsall, user_wallet_list, user_wallet_info, user_order_list, user_submit_order, token_usd_price, user_remove_token } from '@/utils/mixin.ts'
import { Checkbox, Form, Input, message, Spin, Select } from 'antd';
import { useNavigate } from 'react-router-dom';
import DropdownRef from 'antd-mobile/es/components/dropdown';
import send from '@/assets/photos/send-button.png';
import receive from '@/assets/photos/receive-button.png';
import charge from '@/assets/photos/charge-button.png';
import purchase from '@/assets/photos/purchase-button.png';
import { SetOutline } from 'antd-mobile-icons';
import add_import_btn from '@/assets/new/add_import_btn.png';
import profitLoss from '@/assets/new/profit-loss.png';
import refreshButton from '@/assets/new/refresh-button.png'
import { useTranslation } from 'react-i18next';
import BNB from '@/assets/new/BNB.png'
import ETH from '@/assets/new/ETH.png'
import MATIC from '@/assets/new/MATIC.png'
import set from '@/assets/new/set.png'
import del from '@/assets/new/del.png'

import back from '@/assets/new/back.png'
import close from '@/assets/new/close.png'

const Trade = () => {

   

    const { t } = useTranslation();
    const [tabType, setTabType] = useState(0)
    const [numT, setnumT] = useState(0)
    const num = [25, 50 , 75 , 100]
    const [spinning, setSpinning] = React.useState(false);
    const [token_address, set_token_address] = useState(null)
    const [usd_price, set_usd_price] = useState('')
    const [token_price, set_token_price] = useState('')
    const [eth_amount, set_eth_amount] = useState('')
    const [detail, setDetail]  = useState(null) 
    const [selected, SetSelected] = useState(0)

    useEffect(() => {
        const val = JSON.parse(localStorage.getItem('token_address'))
        const detail = JSON.parse(localStorage.getItem('detail'))
        setDetail(detail)
        console.log(val)
        get_token_usd_price(val);
      }, []);  

    const handleChange = (value) => {
        console.log(`selected ${value}`);
        SetSelected(value)
    };
    const get_token_usd_price = (val) => {
        setSpinning(true);
        set_token_address(val)
        token_usd_price({
          token_address :val.token_address,
          network: val.chain
        }).then(res => {
          if(res.code == 0) {
            set_usd_price(res.data)
          }else {
            message.error(res.msg)
          }
          setSpinning(false);
        })
      }

      const switchImg = (val) => {
        let icon = ''
        switch (detail && detail.symbol) {
          case 'BNB':
            icon = BNB
          break;
          case 'ETH':
            icon = ETH
          break;
          case 'MATIC':
            icon = MATIC
          break;
        }
        return icon
      }

    const changeTab = () => {
        let type = ''
        if(!selected && !tabType) {
            type = 'buy'
        } else if(selected && !tabType) {
            type = 'limit_buy'
        } else if(selected && tabType) {
            type = 'limit_sell'
        } else if(!selected && tabType) {
            type = 'sell'
        }
        return type
    }

    const submit = () => {
        let pro = localStorage.getItem('checked')
        pro = pro && JSON.parse(pro)
        if(!eth_amount) {
            return message.error('请输入正确内容')
        }
        if(selected && !token_price) {
            return message.error('请输入正确内容')
        }
        setSpinning(true);
        user_submit_order({
            network: token_address.chain,
            type: changeTab(),
            ...token_address,
            token_price,
            eth_amount,
            is_anti_mev: pro ? 1 : 0
          }).then(res => {
            if(res.code == 0) {
              message.success(t('Operation successful'))
            } else if (res.msg == 'insufficient_funds'){
              message.error(t('balance'))
            }else {
              message.error('持仓不足')
            }
            setSpinning(false);
            set_token_price('')
            set_eth_amount('')
          })
    }

    const computer = (val) => {
        setnumT(val)
        console.log(detail.balance, (val/100) , detail.balance * (val/100))
        set_eth_amount(detail.balance * (val/100))
    }

  return (
        <div className='trade-content'>
             <Spin spinning={spinning} fullscreen />
            <div className='head'>
                <img src={back} onClick={() => window.history.go(-1)} />
                {/* <img src={close} /> */}
                <span></span>
            </div>
            <h4>
                交易
            </h4>
            <div className='trade-main'>
              <div className='trade-tab'>
                <div className={tabType ? 'but' : 'but activeBlue'} onClick={() => setTabType(0)}>买入</div>
                <span></span>
                <div className={tabType ? 'but  activeYellow' : 'but'} onClick={() => setTabType(1)} >卖出</div>
              </div>
              <Select
                defaultValue={0}
                style={{ width: 120 }}
                onChange={handleChange}
                options={[
                    { value: 0, label: '即时交易' },
                    { value: 1, label: '限价交易' },
                ]}
                />

                <div className='price'>
                    <p>
                        价格
                    </p>
                    <div className='inp'>
                       <img src={switchImg()} />  {token_address && token_address.token_name}: {usd_price}
                    </div>
                    <p>
                    {token_address && token_address.token_name}余额： {token_address && token_address.token_quantity}
                    </p>
                </div>

                <div className='num'>
                   {!!selected && <p>
                       输入价格
                    </p>}
                    { !!selected && <Input value={token_price} onChange={(e) => { set_token_price(e.target.value) }} placeholder="" />}
                    <p>
                       输入BNB数量
                    </p>
                    <Input value={eth_amount} onChange={(e) => { set_eth_amount(e.target.value) }}  placeholder="" />
                    <div className='num-tab'>
                        {
                            num.map(item => {
                                return <li className={numT == item ? 'active' : ""} onClick={() => {computer(item)}}>
                                    {item}%
                                </li>
                            })
                        }
                    </div>
                    <span>
                       {detail && detail.symbol}余额： {detail && detail.balance}
                    </span>
                </div>

                <button onClick={() => submit()}>
                    确认
                </button>
            </div>
            
        </div>
  );
};

export default Trade;
